package com.fay.designPattern.pattern.create.prototype;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title:
 * @Description:
 * @Author Fay Wang
 * @Date 2022/4/14 14:07
 * @Version 1.0
 */
public class Demo2 {
    private Map<String, SearchWord> currentKeywords = new HashMap<>();
    private long lastUpdateTime = 1;

    public void refresh() {
        // 原型：拷贝已有对象数据，更新少量差值
        Map<String, SearchWord> newKeywords = (HashMap<String, SearchWord>) (currentKeywords);

        // 从数据库中取出时间>lastUpdateTime的数据，放入到currentKeywords中
        List<SearchWord> toBeUpdatedSearchWords = getSearchWords(lastUpdateTime);
        long maxNewUpdatedTime = lastUpdateTime;
        for (SearchWord searchWord : toBeUpdatedSearchWords) {
            if (searchWord.getLastUpdateTime() > maxNewUpdatedTime) {
                maxNewUpdatedTime = searchWord.getLastUpdateTime();
            }
            if (newKeywords.containsKey(searchWord.getKeyword())) {
                SearchWord oldSearchWord = newKeywords.get(searchWord.getKeyword());
                oldSearchWord.setCount(searchWord.getCount());
                oldSearchWord.setLastUpdateTime(searchWord.getLastUpdateTime());
            }else{
                newKeywords.put(searchWord.getKeyword(), searchWord);
            }
        }
        lastUpdateTime = maxNewUpdatedTime;
        currentKeywords = newKeywords;
    }

    private List<SearchWord> getSearchWords(long lastUpdateTime) {
        // TODO:从数据库中取出更新时间>lastUpdateTime的数据
        return null;
    }
}
